import { getStorage, removeStorage, setStorage } from '@/utils/storage.js'
import { refreshToken } from '@/api/auth'
import axios from 'axios'

let loading = null

const TIME_OUT = 9999999999
const BASE_URL = import.meta.env.VITE_BASE_URL

import { openMessage } from "@/utils/index.js";
// 1. 创建新的axios实例，
const service = axios.create({
  // 超时时间 单位是ms，这里设置了3s的超时时间
  timeout: TIME_OUT,
  baseURL: BASE_URL
})

const serviceshed = []
// 2.请求拦截器
service.interceptors.request.use(
  (config) => {
    if (isExist(config.url)) return null
    serviceshed.push(config.url)


    console.log(config)

    if (config.setting.json) {
      config.headers = {
        'Content-Type': 'application/json' // 配置请求头
      }
    } else {
      config.headers = {
        'Content-Type': 'multipart/form-data' // 配置请求头
      }
    }
    if (config.setting.responseType) {
      config.responseType = config.setting.responseType
    }

    const isToken = config.setting?.isToken
    if (isToken) {
      const token = getStorage('TOKEN')
      config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    const tenantId = getStorage('TENANT_ID')
    if (tenantId) {
      config.headers['tenant-id'] = tenantId
    }
    const params = config.params || {}

    if ((config.method?.toUpperCase() === 'GET' || config.method?.toUpperCase() === 'DELETE')) {
      let url = config.url
      // 合并 params、config.params 和 data
      const allParams = {
        ...(params || {}),
        ...(config.params || {}),
        ...(typeof config.data === 'string' ? JSON.parse(config.data || '{}') : (config.data || {}))
      }

      // 只有在有参数时才添加问号
      if (Object.keys(allParams).length > 0) {
        url += '?'

        for (const propName of Object.keys(allParams)) {
          const value = allParams[propName]
          if (value !== null && typeof value !== 'undefined') {
            if (typeof value === 'object') {
              for (const val of Object.keys(value)) {
                const paramKey = propName + '[' + val + ']'
                const subPart = encodeURIComponent(paramKey) + '='
                url += subPart + encodeURIComponent(value[val]) + '&'
              }
            } else {
              url += `${propName}=${encodeURIComponent(value)}&`
            }
          }
        }

        // 移除最后一个 & 符号
        url = url.endsWith('&') ? url.slice(0, -1) : url
      }

      // 清空原有的参数，防止重复添加
      config.params = null
      config.data = null
      config.url = url
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (config) => {
    loading ? loading.close() : ''
    removeShed(config.url)
    if (config?.config?.setting?.responseType) {
      return config
    }
    if (config.data.code === 401) {
      let refresh_token = getStorage('REFRESH_TOKEN')
      if (refresh_token) {
        //刷新token
        refreshToken({ refresh_token }).then((res) => {
          if (res.code === 200) {
            //先删除
            removeStorage('TOKEN')
            removeStorage('REFRESH_TOKEN')
            //再添加
            setStorage('TOKEN', res.data.access_token)
            setStorage('REFRESH_TOKEN', res.data.refresh_token)
            window.location.reload()
          } else {

            removeStorage('TOKEN')
            removeStorage('REFRESH_TOKEN')
            window.location = `${window.location.origin + window.location.pathname}#/login`
          }
        })
      } else {
        removeStorage('TOKEN')
        removeStorage('REFRESH_TOKEN')
        window.location = `${window.location.origin + window.location.pathname}#/login`
      }
    } else if (config.data.code !== 200) {
      openMessage(config.data.message, 'error')
    }
    return config.data || {}
  },
  (error) => {
    console.log(error, 'error')
    loading ? loading.close() : ''
    return {}
  }
)

const isExist = (url) => {
  return serviceshed.find((ele) => ele == url)
}

const removeShed = (url) => {
  const index = serviceshed.findIndex((ele) => ele == url)
  serviceshed.splice(index, 1)
}

// 4.导入文件
export default service
